<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>
    <script src="../js/utils.js"></script>
</head>

<body>
    <h3>登录</h3>
    <p>帐号:<input type="text" id="username"></p>
    <p>密码:<input type="password" id="pwd"></p>
    <button>登录</button>
    <script>
        let btn = document.querySelector('button')
        let loginName = document.getElementById('username')
        let loginPwd = document.getElementById('pwd')
        btn.onclick = () => {
            let username = loginName.value
            let pwd = loginPwd.value
            // console.log(username,pwd)
            let xhr = new XMLHttpRequest()
            xhr.open("post", '..//api/v1/users/login.php')
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(`username=${username}&pwd=${pwd}`)
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status == 200) {
                        let msg = JSON.parse(xhr.responseText)
                        console.log(msg)
                        if (msg.code === 200) {
                            let obj = { path: '/' }
                            //七天与否
                            if (false) {
                                obj.expires = '7'
                            }
                            utils.setCookie('loginState', 'on', obj)
                            utils.setCookie('username', username, obj)
                            alert('登录成功')
                            window.location.href = '../index.html'
                        } else if (msg.code === 400) {
                            alert('帐号或密码错误')
                        }else{
                            alert('网络错误，请稍后再次尝试')
                        }
                    }
                }
            }
        }

    </script>
</body>

</html>